import {Control} from "react-keeper";

require('./PageDbrwtx.styl');

import {PropTypes} from "prop-types";
import {is} from 'immutable'
import {Avatar, Boxs, Group, Scroller, ScrollList, SearchBar, Tab} from 'saltui';
import Icon from 'salt-icon';
import Reflux from 'reflux';
import nattyStorage from 'natty-storage';
const {API_URL} = require(`./../../config/${ENV}.json`);
const reactMixin = require('react-mixin');
const Actions = require('./actions');
const Store = require('./store');
const HBox = Boxs.HBox;
const Box = Boxs.Box;
const avatarColors = ['#78C06E', '#3BC2B5', '#78919D', '#5EC9F6', '#F6BF26'];

const storageScroll = nattyStorage({
  type: 'localStorage',  // 缓存方式, 默认为'localStorage'
  key: 'sskj-dingtalk-scroll',     // !!! 唯一必选的参数, 用于内部存储 !!!
});

const Item = (props) => {

  let jdrysAvatar = [];
  return <Group.List>
    <div className='jcjl-t-list-wrap'  onClick={() => {
      props.click(props.data);
    }}>
      <HBox vAlign="center">
        <HBox flex={1}>
          <Box style={{width: '55px'}}>
            {/*<img src="https://img.alicdn.com/tps/TB1eoLXJFXXXXaFXVXXXXXXXXXX-60-60.png" className="demo-t-list-img" />*/}
            <Avatar name={props.tjrName} />
          </Box>
          <Box>
            <p className='jcjl-t-list-eng-title t-omit2'>
              <span>{props.engName}</span></p>
            <p className='jcjl-t-list-title'></p>

            <p className='jcjl-t-list-title' style={{marginTop:'10px'}}>
              <span className="jllx">{props.txName}</span>

            </p>
            <p className='jcjl-t-list-title' style={{marginTop:'10px'}}>
              <span>{props.kssj}</span>
            </p>
          </Box>
        </HBox>
      </HBox>
    </div>
  </Group.List>
};


class Page extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      keyword: '',
      height: window.innerHeight,
      activeUploadIndex: 0,
    };
    this.onRwSearchEnter = this.onRwSearchEnter.bind(this);
    this.onRwSearchExit = this.onRwSearchExit.bind(this);
    this.handleRefresh = this.handleRefresh.bind(this);
    this.onSearchBlur = this.onSearchBlur.bind(this);
    this.onRouteCase = this.onRouteCase.bind(this);
  }

  onRouteCase(obj) {
    console.log(obj);
    Control.go('/dbrwedit',obj);
    //this.context.router.push(`dbrwedit/${obj.spId}`);
/*    dd.biz.util.openLink({
      url: obj.route,
      onSuccess: function (result) {

      },
      onFail: function (err) {
        alert(JSON.stringify(err));
      }
    });*/
  }



  //调用 IScroll refresh 后回调函数
  handleRefresh(downOrUp, callback) {
    Actions.rwFetch({
      page: this.props.page,
      noRemove: true,
      downOrUp: downOrUp
    }, callback);
  }

  //页签TAB切换事件
  onTabChange(obj) {

    if (obj.active == 0) {
      Actions.tabChange(false);
      this.refs.nScrollList.fetchData('top');
    } else {
      Actions.tabChange(true);
      this.refs.yScrollList.fetchData('top');
    }
  }


  onRwSearchEnter() {
    let t = this;
    this.refs.rwsearch.refs.input.addEventListener('blur', this.onSearchBlur);
  }

  onSearchBlur() {
    this.setState({
      height: window.innerHeight,
    });
  }

  onRwSearchExit() {
    this.setState({
      height: window.innerHeight,
    });
    window.scrollTo(0, 0);
    this.refs.rwsearch.refs.input.removeEventListener('blur', this.onSearchBlur);
    this.props.onJdjlSearchExit();
  }


  render() {

    let t = this;
    //列表页
    let lis = [];
    //搜索页
    let slis = [];

    let items = [];

    let sItems = [];

    if (this.state.activeUploadIndex == 0) {
      sItems = this.state.searchnRwsItems;
      items = this.state.nRwsItems;
    } else {
      sItems = this.state.searchuRwsItems;
      items = this.state.uRwsItems;
    }


    items && items.forEach((item, index) => {


      lis.push(
        <Group.List>
          <div className='demo3-t-list-wrap' key={index}>
            <HBox vAlign="center">
              <HBox flex={1}>
                <Box style={{width:'55px'}}>
                  <Avatar name={item.get('tjrName')} colors={avatarColors} key={index}
                          src=''/>
                </Box>
                <Box flex={1}>
                  <p style={{fontWeight:'bold'}} onClick={(e) => {
                                        // Toast.show({
                                        //     type: 'loading',
                                        //     content: '加载中...',
                                        //     autoHide: false,
                                        //     hasMask: true
                                        // });
                                        storageScroll.set('rwScroll',this.refs.iScroll.iScrollInstance.y);
                                        this.context.router.push(`dbrwtxedit/${item.get('spId')}`);


                                }} className='txrw-t-list-title t-omit'>{item.get('rwName')}
                  </p>
                  <p className='txrw-t-list-content'>
                    提交人: {item.get('tjrName') == t.state.user.get('name') ? '我' : item.get('tjrName')}</p>
                  <p className='txrw-t-list-content'>开始时间: {item.get('kssj')}</p>
                  <p className='txrw-t-list-content'>结束时间: {item.get('ywcsj')}</p>
                  <p className='txrw-t-list-zt'>{item.get('isEnd') ? '已处理' : '待处理'}</p>
                </Box>
              </HBox>
            </HBox>
          </div>
        </Group.List>
      );
    });

    return (
      <div className="dbrwtx">

        <Tab activeKey={'0'}
             onChange={this.onTabChange.bind(this)}
             className="engSearchBar">
          <Tab.Item title="待我处理">


              <div className="container" style={{height: window.innerHeight - 5}}>
                <ScrollList
                  ref="nScrollList" scrollRefresh={false}
                  url={API_URL + '/jd/txrw/dbsh/page'}
                  pageSize={10}
                  dataType="json"
                  currentPageKey="page"
                  beforeFetch={(data) => {

                    return {
                      page: data.page,
                      size: data.pageSize,
                      isRun: 0,
                      userid: this.state.dbrw.user.get('userid') ? this.state.dbrw.user.get('userid') : ''
                    }
                  }}
                  processData={(data) => {
                    console.info('data数据',data );
                    return data
                  }}>
                  <Item click={this.onRouteCase} />
                </ScrollList>
              </div>
          </Tab.Item>
          <Tab.Item title="我已处理">
            <div className="container" style={{height: window.innerHeight - 5}}>
              <ScrollList
                ref="nScrollList" scrollRefresh={false}
                url={API_URL + '/jd/txrw/dbsh/page'}
                pageSize={10}
                dataType="json"
                currentPageKey="page"
                beforeFetch={(data) => {

                  return {
                    page: data.page,
                    size: data.pageSize,
                    isRun: 1,
                    userid: this.state.dbrw.user.get('userid') ? this.state.dbrw.user.get('userid') : ''
                  }
                }}
                processData={(data) => {
                  return data
                }}>
                <Item click={this.onRouteCase} />
              </ScrollList>
            </div>
          </Tab.Item>
        </Tab>

      </div>
    );
  }


  componentDidMount() {
    let t = this;

    // Toast.hide(function () {
    //
    // });

    // if (storageScroll.has('rwScroll').has) {
    //   this.refs.iScroll.iScrollInstance.scrollTo(0, storageScroll.get('rwScroll'));
    //   storageScroll.remove();
    // }

    dd.biz.navigation.setTitle({
      title: '待办事项',//控制标题文本，空字符串表示显示默认文本
      onSuccess: function (result) {
      },
      onFail: function (err) {
      }
    });

    dd.biz.navigation.setLeft({
      show: true,//控制按钮显示， true 显示， false 隐藏， 默认true
      control: true,//是否控制点击事件，true 控制，false 不控制， 默认false
      text: '返回',//控制显示文本，空字符串表示显示默认文本
      onSuccess: function (result) {

        dd.ui.nav.close({
          onSuccess: function (result) {

          },
          onFail: function (err) {
            console.log(err);
            alert("调用钉钉接口错误:" + JSON.stringify(err));
          }
        })

      },
      onFail: function (err) {
        console.log(err);
        alert("调用钉钉接口错误:" + JSON.stringify(err));
      }
    });

    dd.biz.navigation.setRight({
      show: false,//控制按钮显示， true 显示， false 隐藏， 默认true
      control: false,//是否控制点击事件，true 控制，false 不控制， 默认false
      text: '',//控制显示文本，空字符串表示显示默认文本
      onSuccess: function (result) {

      },
      onFail: function (err) {
      }
    });

  }

  componentWillMount() {

    let t = this;

    Actions.rwInit();

    dd.biz.navigation.setTitle({
      title: '任务查询',//控制标题文本，空字符串表示显示默认文本
      onSuccess: function (result) {
      },
      onFail: function (err) {
        console.log(err);
        alert("调用钉钉设置导航接口错误:" + JSON.stringify(err));
      }
    });

    this.setState({
      height: window.innerHeight,
    });
  }

  componentDidUpdate() {
    //this.refs.iScroll.iScrollInstance.refresh();
    return true;
  }

  shouldComponentUpdate(nextProps = {}, nextState = {}) {
    const thisProps = this.props || {},
      thisState = this.state.dbrwtx || {};

    if (Object.keys(thisProps).length !== Object.keys(nextProps).length ||
      Object.keys(thisState).length !== Object.keys(nextState).length) {
      return true;
    }

    for (const key in nextProps) {
      if (thisProps[key] !== nextProps[key] || !is(thisProps[key], nextProps[key])) {
        console.log(thisProps[key], nextProps[key]);
        return true;
      }
    }

    for (const key in nextState) {
      if (thisState[key] !== nextState[key] || !is(thisState[key], nextState[key])) {
        return true;
      }
    }
    return false;
  }
}


Page.contextTypes = {
  router: PropTypes.object.isRequired,
  location: PropTypes.object.isRequired,
};

reactMixin.onClass(Page, Reflux.connect(Store, "dbrw"));

export default Page;


